﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Pikapika
{
    public static class ThumbnailExtensions
    {
        public static MvcHtmlString ThumbnailImage(this HtmlHelper helper, string url, int maxWidth, int maxHeight)
        {
            return ThumbnailImage(helper, url, maxWidth, maxHeight, false);
        }
        public static MvcHtmlString ThumbnailImage(this HtmlHelper helper, string url, int maxWidth, int maxHeight, bool includeOriginalLink)
        {
            if (helper == null)
                throw new ArgumentNullException("helper", "helper is null.");
            if (String.IsNullOrEmpty(url))
                throw new ArgumentException("url is null or empty.", "url");

            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://",StringComparison.OrdinalIgnoreCase))
            {
                // external image, we can't generate thumbnail for it
                return GenerateHtml(url, includeOriginalLink ? url : null);
            }
            var thumbnailUrl = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action("Generate", "Thumbnail", new RouteValueDictionary { { "pathInfo", url }, { "maxWidth", maxWidth }, {"maxHeight", maxHeight} });
            return GenerateHtml(thumbnailUrl, includeOriginalLink ? url : null);
        }

        private static MvcHtmlString GenerateHtml(string imageUrl, string linkUrl)
        {
            if (String.IsNullOrEmpty(imageUrl))
                throw new ArgumentException("imageUrl is null or empty.", "imageUrl");

            var tagBuilder = new TagBuilder("img");
            tagBuilder.MergeAttribute("src", imageUrl);
            string imgHtml = tagBuilder.ToString(TagRenderMode.SelfClosing);
            if (linkUrl == null)
            {
                return new MvcHtmlString(imgHtml);
            }
            tagBuilder = new TagBuilder("a");
            tagBuilder.InnerHtml = imgHtml;
            tagBuilder.MergeAttribute("href", linkUrl);
            tagBuilder.MergeAttribute("target", "_blank");
            tagBuilder.MergeAttribute("title", "点击查看原图");
            return new MvcHtmlString(tagBuilder.ToString());
        }
    }
}